# -*- coding: utf-8 -*-
"""
模块：模板及用户贺卡数据与JSON文件的读写操作
邓深耀负责D部分
"""
import json
import os
from datetime import datetime
import time

DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
TEMPLATES_FILE_PATH = os.path.join(DATA_DIR, "templates.json")
MY_ECARDS_FILE_PATH = os.path.join(DATA_DIR, "my_ecards.json")


def load_templates():
    """加载模板数据"""
    if os.path.exists(TEMPLATES_FILE_PATH):
        try:
            with open(TEMPLATES_FILE_PATH, 'r', encoding='utf-8') as f:
                return json.load(f)
        except (json.JSONDecodeError, IOError):
            print("警告：模板文件读取失败，使用内置模板")
    
    # 如果文件不存在或读取失败，使用硬编码模板
    from template_manager import load_templates_internal
    return load_templates_internal()

def load_my_ecards():
    """加载用户保存的贺卡"""
    if not os.path.exists(MY_ECARDS_FILE_PATH):
        return []
        
    try:
        with open(MY_ECARDS_FILE_PATH, 'r', encoding='utf-8') as f:
            return json.load(f)
    except (json.JSONDecodeError, IOError):
        print("警告：我的贺卡文件读取失败，将使用空列表")
        return []

def save_my_ecard(ecard_data_to_save):
    """保存用户贺卡"""
    my_ecards = load_my_ecards()
    
    # 生成ID和时间戳
    ecard_id = f"ecard_{int(time.time())}"
    saved_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    # 构建完整数据
    ecard_data = {
        "ecard_id": ecard_id,
        "saved_at": saved_at,
        **ecard_data_to_save
    }
    
    my_ecards.append(ecard_data)
    
    try:
        with open(MY_ECARDS_FILE_PATH, 'w', encoding='utf-8') as f:
            json.dump(my_ecards, f, ensure_ascii=False, indent=2)
        print(f"贺卡已保存，ID: {ecard_id}")
    except IOError:
        print("警告：贺卡保存失败")

def view_my_saved_ecards_interaction():
    """查看已保存贺卡交互"""
    my_ecards = load_my_ecards()
    
    if not my_ecards:
        print("\n您还没有保存任何贺卡！")
        return
        
    print("\n" + "=" * 30)
    print("我的贺卡列表")
    print("=" * 30)
    for idx, ecard in enumerate(my_ecards, 1):
        print(f"{idx}. ID: {ecard['ecard_id']}")
        print(f"   模板: {ecard['template_used']}")
        print(f"   保存时间: {ecard['saved_at']}")
    print("=" * 30)
    
    while True:
        choice = input("请输入要查看的贺卡编号(1-{})，或输入0返回: ".format(len(my_ecards))).strip()
        if choice == "0":
            break
            
        try:
            idx = int(choice) - 1
            if 0 <= idx < len(my_ecards):
                print("\n" + "=" * 30)
                print(f"贺卡内容 (ID: {my_ecards[idx]['ecard_id']})")
                print("=" * 30)
                print(my_ecards[idx]['generated_text'])
                print("=" * 30)
                input("\n按Enter键返回...")
                break
            print("无效的编号，请重新输入！")
        except ValueError:
            print("请输入有效的数字！")